package com.hutao.medical.controller.statics;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.medical.common.util.CookieUtils;
import com.hutao.medical.common.util.DateUtil;
import com.hutao.medical.common.util.ExcelUtil;
import com.hutao.medical.common.util.JsonUtils;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.pojo.dto.MedRetireDto;
import com.hutao.medical.query.QueryManageVo;
import com.hutao.medical.query.SearchVo;
import com.hutao.medical.service.BasicService;
import com.hutao.medical.service.MedRecordService;
import com.hutao.medical.service.StatiService;

/**
 * 病案检索controller
 */
@Controller
@RequestMapping("/retrieval")
public class MedRecordRetrievalController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BasicService basicService;

	@Autowired
	private MedRecordService medRecordService;

	@Autowired
	private StatiService statiService;
	
	

	@RequestMapping("/medRetrieval")
	public String medRetrieval(Model model) {
		Map<String, List<java.util.Map<String, Object>>> map = medRecordService.getBaseInfoMap();
		/*
		 * if(MapUtils.isNotEmpty(map)){
		 * model.addAttribute("officeJson",JsonUtils.objectToJson(map.get(
		 * "offices"))); model.addAttribute("outHospitalList",
		 * map.get("outHospitalList")); model.addAttribute("sexes",
		 * map.get("sexes")); }
		 */
		List<Map<String, Object>> outHospitalTypeList = basicService.getOutHospitalType();
		List<Map<String, Object>> officeJson = basicService.getHospitalOffice();
		model.addAttribute("officeJson", JsonUtils.objectToJson(officeJson));
		model.addAttribute("outHospitalTypeList", outHospitalTypeList);
		return "query/queryMedRetrieval ";
	}

	@ResponseBody
	@RequestMapping("/getDiseaseByCodeAndName")
	public List<Map<String, Object>> getDiseaseByCodeAndName(String name) {
		return statiService.getDiseaseByCodeOrName(name);
	}

	@ResponseBody
	@RequestMapping("/getOperationByCodeAndName")
	public List<Map<String, Object>> getOperationByCodeAndName(String name) {
		return statiService.getOperationByCodeOrName(name);
	}

	/**
	 * 临床检索页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryClinic")
	public String queryClinic() {
		return "query/queryclinic";
	}

	// 临床检索详情页面
	@RequestMapping("/queryClinic_index")
	public String queryClinic_index(Model model,HttpServletRequest request) {
		
		String officeName = CookieUtils.getCookieValue(request, "officeName");

		//Map<String, List<Map<String, Object>>> basicInfoList = basicService.getBasicInfoList();
		model.addAttribute("officeName", officeName);
		return "query/queryclinic_index";
	}

	// 临床检索详情页面
	@RequestMapping("/queryManage_index")
	public String queryManage_index(Model model) {

		Map<String, List<Map<String, Object>>> basicInfoList = basicService.getBasicInfoList();
		model.addAttribute("basicInfoList", basicInfoList);
		return "query/querymanage_index";
	}

	// 特殊检索详情页面
	@GetMapping("/specialSearches_index")
	public String specialSearches_index(Model model) {
		Map<String, List<Map<String, Object>>> basicInfoList = basicService.getBasicInfoList();
		model.addAttribute("basicInfoList", basicInfoList);
		return "query/specialSearch_index";
	}

	/**
	 * 管理检索页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryManage")
	public String queryManage() {
		return "query/querymanage";
	}

	// 特殊检索登录页面
	@GetMapping("/specialSearches")
	public String specialSearches() {
		return "query/specialSearch";
	}

	@ResponseBody
	@RequestMapping("/clinicalRetrieval")
	public Result clinicalRetrieval(MedRetireDto medRetireDto) {
		Result result = null;
		try {
			Map<String, Object> map = new HashMap<>();
			List<Map<String, Object>> list = new ArrayList<>();
			List<String> jsonList = statiService.getClinicalRetrievalList(medRetireDto);
			int count = statiService.getClinicalRetrievalCount(medRetireDto);
			if (CollectionUtils.isNotEmpty(jsonList)) {
				for (String json : jsonList) {

					list.add(JsonUtils.jsonToPojo(json, Map.class));
				}
			}
			map.put("jsonList", list);
			map.put("count", count);
			result = new Result(true, "查询成功", map);
		} catch (Exception e) {
			logger.info("临床检索查询数据时出现错误:{}=" + e.getMessage());
			result = new Result(false);
		}
		return result;
	}

	/**
	 * 入院统计报表
	 * 
	 * @return
	 */
	@ResponseBody
	@GetMapping("/admissionStatistics")
	public Map<String, Object> admissionStatistics(HttpServletRequest request) {
		Map<String, Object> resultValueMap = new HashMap<>();
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");

		// 入院统计
		List<Map<String, Object>> admissionStatisticsList = medRecordService.admissionStatistics(beginDate, endDate);
		// 入院途径
		List<Map<String, Object>> inHospitalTypeList = basicService.getInHospitalType();

		resultValueMap.put("admissionStatisticsList", admissionStatisticsList);
		resultValueMap.put("inHospitalTypeList", inHospitalTypeList);

		return resultValueMap;
	}
	
	//统计入院途径导出excel
	@RequestMapping("/exportInHospitalRouteExcel")
	public void exportInHospitalRouteExcel(HttpServletResponse response,HttpServletRequest request){
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			String excelName = beginDate+"--"+endDate+"入院途径统计信息";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			
			// 入院统计
			List<Map<String,Object>> list = medRecordService.inHospitalRouteExcelList(beginDate, endDate);
			
			
			
			
			
			String title = excelName;
			String[] header = { "入院类型", "数量", "百分比" };
			ExcelUtil.exportExcel(out, title,  header, list);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	
	
	

	/**
	 * 从事职业构成统计
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@GetMapping("/makeACareerStatistics")
	public Map<String, Object> makeACareerStatistics(HttpServletRequest request) {
		Map<String, Object> resultValueMap = new HashMap<>();
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");

		// 从事职业统计
		List<Map<String, Object>> makeACareerStatisticsList = medRecordService.makeACareerStatistics(beginDate,
				endDate);
		resultValueMap.put("makeACareerStatisticsList", makeACareerStatisticsList);

		return resultValueMap;
	}
	
	/**
	 * 从事职业信息导出excel
	 * @param request
	 * @param response
	 */
	@RequestMapping("/exportJobExcel")
	public  void exportJobExcel(HttpServletRequest request,HttpServletResponse response){
		
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");

			String excelName = beginDate+"--"+endDate+"职业信息统计";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String,Object>> officeWokeList = medRecordService.occpationExcelList(beginDate, endDate);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title =excelName;
			String[] header = { "职业", "数量", "所占比率"};
			ExcelUtil.exportExcel(out, title,  header, officeWokeList);
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
	}
	
	

	/**
	 * 付费方式统计
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@GetMapping("/wayOfPayingStatistics")
	public Map<String, Object> wayOfPayingStatistics(HttpServletRequest request) {
		Map<String, Object> resultValueMap = new HashMap<>();
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");

		// 付费方式类型
		List<Map<String, Object>> wayOfPayingTypeList = basicService.getWayOfPayingType();
		// 付费方式统计
		List<Map<String, Object>> wayOfPayingStatisticsList = medRecordService.wayOfPayingStatistics(beginDate,
				endDate);
		resultValueMap.put("wayOfPayingTypeList", wayOfPayingTypeList);
		resultValueMap.put("wayOfPayingStatisticsList", wayOfPayingStatisticsList);

		return resultValueMap;
	}
	
	@RequestMapping("/paymentExcel")
	public  void  paymentExcel(HttpServletRequest request,HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			String excelName = beginDate+"--"+endDate+"付费方式统计信息";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			
			// 入院统计
			List<Map<String,Object>> list = medRecordService.paymentExcelList(beginDate, endDate);
			
			
			
			
			
			String title = "付费方式统计信息";
			String[] header = { "付款方式类型", "数量", "所占比率" };
			ExcelUtil.exportExcel(out, title,  header, list);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	

	/**
	 * 拼装字典信息
	 * 
	 * @param model
	 */
	public void assemDicList(Model model) {
		List<Map<String, Object>> inHospitalStateList = basicService.getInHospitalState();
		// List<Map<String,Object>>
		// hospitalOfficeList=basicService.getHospitalOffice();
		// List<Map<String,Object>>
		// outHospitalTypeList=basicService.getOutHospitalType();
		List<Map<String, Object>> diagnoseTypeList = basicService.getDiagnoseType();
		model.addAttribute("inHospitalStateList", inHospitalStateList);
		// model.addAttribute("hospitalOfficeList", hospitalOfficeList);
		// model.addAttribute("outHospitalTypeList", outHospitalTypeList);
		model.addAttribute("diagnoseTypeList", diagnoseTypeList);

		List<Map<String, Object>> outHospitalTypeList = basicService.getOutHospitalType();
		List<Map<String, Object>> officeJson = basicService.getHospitalOffice();
		model.addAttribute("officeJson", JsonUtils.objectToJson(officeJson));
		model.addAttribute("outHospitalTypeList", outHospitalTypeList);
	}

	/**
	 * 诊治疾病顺位
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/diagnosisAndTreatmentOfDiseases")
	public Map<String, Object> diagnosisAndTreatmentOfDiseases(HttpServletRequest request) {
		Map<String, Object> resultValueMap = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		String outDeptName = request.getParameter("outDeptName");
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		params.put("outDeptName", outDeptName);

		List<Map<String, Object>> diagnosisAndTreatmentOfDiseasesList = medRecordService
				.diagnosisAndTreatmentOfDiseases(params);
		resultValueMap.put("diagnosisAndTreatmentOfDiseasesList", diagnosisAndTreatmentOfDiseasesList);

		return resultValueMap;
	}

	/**
	 * 住院手术顺位
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/hospitalizationInLineStatistics")
	public Map<String, Object> hospitalizationInLineStatistics(HttpServletRequest request) {
		Map<String, Object> resultValueMap = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		String outDeptName = request.getParameter("outDeptName");
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		params.put("outDeptName", outDeptName);

		List<Map<String, Object>> hospitalizationInLineList = medRecordService.hospitalizationInLineStatistics(params);
		resultValueMap.put("hospitalizationInLineList", hospitalizationInLineList);

		return resultValueMap;
	}

	/**
	 * 查询2,3,7日归档率统计
	 * 
	 * @param medRetireDto
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getMedRecordPigeonholeRate")
	public Result getMedRecordPigeonholeRate(MedRetireDto medRetireDto) {
		Result result = null;
		try {
			List<Map<String, Object>> list = statiService.getPigeonholeRate(medRetireDto);
			result = new Result(true, "查询成功!", list);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false, "查询失败!");
		}
		return result;
	}
	
	
	@RequestMapping("/exportPigonholeExcel")
	public void exportPigonholeExcel(MedRetireDto medRetireDto,HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			String excelName = "科室归档率";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String, Object>> list = statiService.getPigeonholeRate(medRetireDto);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title = "科室归档率";
			String[] header = { "科室名称", "应归档数", "2日归档数", "2日归档率", "3日归档数", "3日归档率", "7日归档数", "7日归档率" };
			ExcelUtil.exportExcel(out, title,  header, list);

		} catch (Exception e) {
			e.printStackTrace();

		}
		
		
		
	}
	
	

	/**
	 * 查询2,3,7日归档率统计
	 * 
	 * @param medRetireDto
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getShelvedRate")
	public Result getShelvedRate(MedRetireDto medRetireDto) {
		Result result = null;
		try {
			List<Map<String, Object>> list = statiService.getShelvedRate(medRetireDto);
			result = new Result(true, "查询成功!", list);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false, "查询失败!");
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/getMedRecordStatisByOffice")
	public Result getMedRecordStatisByOffice(MedRetireDto medRetireDto) {
		Result result = null;
		try {
			List<Map<String, Object>> list = statiService.getMedRecordStatisByOffice(medRetireDto);
			result = new Result(true, "查询成功!", list);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false, "查询失败!");
		}
		return result;
	}

	// 科室统计
	@RequestMapping("/departmentstatistics")
	public String departmentsCount() {
		return "statics/statistics/departmentstatistics";
	}

	@ResponseBody
	@RequestMapping("/getMedicalRecordRetrieval")
	public Result getMedicalRecordRetrieval(QueryManageVo queryManageVo) {
		Result result = null;
		try {
			Map<String, Object> map = statiService.getMedicalRecordRetrievalMap(queryManageVo);
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			result = new Result(false, "查询失败!");
			e.printStackTrace();
		}
		return result;

	}
	
	@ResponseBody
	@RequestMapping("/getMedicalSpecialRecord")
	public Result getMedicalSpecialRecord(SearchVo searchVo) {
		Result result = null;
		try {
			Map<String, Object> map = statiService.getMedicalSpecialRecord(searchVo);
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			result = new Result(false, "查询失败!");
			e.printStackTrace();
		}
		return result;

	}
	
	
	@ResponseBody
	@RequestMapping("/getOfficeWork")
	public Result getOfficeWork(QueryManageVo queryManageVo) {
		Result result = null;
		try {
			List<Map<String,Object>> officeWokeList = statiService.getOfficeWorkInfo(queryManageVo);
			result = new Result(true, "查询成功!", officeWokeList);
		} catch (Exception e) {
			result = new Result(false, "查询失败!");
			e.printStackTrace();
		}
		return result;

	}
	
	
	
	/**
	 * 导出excel
	 * 
	 * @param params
	 * @return
	 */
	@RequestMapping("/exportOfficeWork")
	public void exportOfficeWork(QueryManageVo queryManageVo, HttpServletResponse response) {
		//List<Map<String, Object>> scanWorkMapList = new ArrayList<>();

		try {
			response.setContentType("octets/stream");
			String excelName = DateUtil.dateToStr(queryManageVo.getOutHospitalStartTime(), "yyyy-MM-dd")+"--"+DateUtil.dateToStr(queryManageVo.getOutHospitalEndTime(), "yyyy-MM-dd")+"临床信息统计信息";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String,Object>> officeWokeList = statiService.getOfficeWorkInfo(queryManageVo);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title = excelName;
			String[] header = { "科室名称", "出院人数", "入院人数", "抢救病人数", "抢救成功人数", "特级护理人数", "病危护理人数","病重护理人数" };
			ExcelUtil.exportExcel(out, title,  header, officeWokeList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	@RequestMapping("/exportFillingExcel")
	public void exportFillingWorkExcel(HttpServletRequest request,HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			String excelName = beginDate+"--"+endDate+"归档工作信息统计";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String,Object>> officeWokeList = medRecordService.fillingWorkExcelList(beginDate, endDate);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title = "归档工作信息统计";
			String[] header = { "姓名", "归档数量", "归档所占比"};
			ExcelUtil.exportExcel(out, title,  header, officeWokeList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	
	@RequestMapping("/exportMedQualityWorkExcel")
	public void exportMedQualityWorkExcel(HttpServletRequest request,HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			String excelName = beginDate+"--"+endDate+"质控工作信息统计";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String,Object>> officeWokeList = medRecordService.qualityWorkExcelList(beginDate, endDate);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title = "质控工作信息统计";
			String[] header = { "姓名", "质控数量", "质控所占比"};
			ExcelUtil.exportExcel(out, title,  header, officeWokeList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	
	
	
	
	@RequestMapping("/exportPaginationWorkExcel")
	public void exportPaginationWorkExcel(HttpServletRequest request,HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			String excelName = beginDate+"--"+endDate+"编页工作信息统计";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String,Object>> officeWokeList = medRecordService.paginationWorkExcelList(beginDate, endDate);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title = "编页工作信息统计";
			String[] header = { "姓名", "编页数量", "编页所占比"};
			ExcelUtil.exportExcel(out, title,  header, officeWokeList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	
	

	@RequestMapping("/exportCatalogerWorkExcel")
	public void exportCatalogerWorkExcel(HttpServletRequest request,HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			String excelName = beginDate+"--"+endDate+"编目工作信息统计";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();
			List<Map<String,Object>> officeWokeList = medRecordService.catalogeExcelList(beginDate, endDate);
			// 查询数据
			//scanWorkMapList = this.generateData();
			String title = "编目工作信息统计";
			String[] header = { "姓名", "编页数量", "编页所占比"};
			ExcelUtil.exportExcel(out, title,  header, officeWokeList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	

}
